package handler

import (
	"api/common"
	"api/internal/request"
	"fmt"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	pb "group_server/proto"
)

func GetGroupList(c *gin.Context) {
	value, _ := c.Get("userId")
	id := value.(uint)
	client, err := grpc.NewClient("127.0.0.1:50052", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		common.JsonRes(c, 400, "grpc连接失败", nil)
		return
	}
	req := &pb.GetGroupListReq{UserId: int64(id)}
	con := pb.NewGroupClient(client)
	list, err := con.GetGroupList(c, req)
	if err != nil {
		common.JsonRes(c, 400, err.Error(), nil)
		return
	}
	common.JsonRes(c, 200, "获取成功", list)
}

func GroupCreate(c *gin.Context) {
	json := request.GroupCreateRequest{}
	err := c.ShouldBindJSON(&json)
	if err != nil {
		common.JsonRes(c, 400, "请求参数错误", nil)
		return
	}
	client, err := grpc.NewClient("127.0.0.1:50052", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		common.JsonRes(c, 400, "grpc连接失败", nil)
		return
	}
	req := &pb.GroupCreateReq{
		Name:  json.Name,
		Price: float32(json.Price),
		Num:   int64(json.Num),
	}
	con := pb.NewGroupClient(client)
	list, err := con.GroupCreate(c, req)
	if err != nil {
		common.JsonRes(c, 400, err.Error(), nil)
		return
	}
	common.JsonRes(c, 200, "创建成功", list)
}

func OrderCreate(c *gin.Context) {
	value, _ := c.Get("userId")
	id := value.(uint)
	json := request.OrderCreateRequest{}
	err := c.ShouldBindJSON(&json)
	if err != nil {
		common.JsonRes(c, 400, "请求参数错误", nil)
		return
	}
	client, err := grpc.NewClient("127.0.0.1:50052", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		common.JsonRes(c, 400, "grpc连接失败", nil)
		return
	}
	req := &pb.OrderCreateReq{
		UserId:  int64(id),
		GoodId:  int64(json.GoodId),
		Num:     int64(json.Num),
		Payment: json.Payment,
	}
	con := pb.NewGroupClient(client)
	list, err := con.OrderCreate(c, req)
	if err != nil {
		common.JsonRes(c, 400, err.Error(), nil)
		return
	}
	common.JsonRes(c, 200, "创建成功", list)
}

func OrderBack(c *gin.Context) {
	sn := c.PostForm("out_trade_no")
	client, err := grpc.NewClient("127.0.0.1:50052", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		common.JsonRes(c, 400, "grpc连接失败", nil)
		return
	}
	status := c.PostForm("notify_type")
	fmt.Println(sn, status)
	if status == "trade_status_sync" {
		req := &pb.OrderUpdateReq{
			Sn:     sn,
			Status: status,
		}
		con := pb.NewGroupClient(client)
		update, err := con.OrderUpdate(c, req)
		if err != nil {
			common.JsonRes(c, 400, err.Error(), nil)
			return
		}
		common.JsonRes(c, 200, "创建成功", update)
	}

}
